import React, { PureComponent} from 'react';
import PropTypes from "prop-types";
import XEUtils from 'xe-utils'
class ErrorCatch extends PureComponent {
    state = {
        user_list: [
            {id: 1, name: '小明'},
            {id: 2, name: '小红'},
            {id: 3, name: '小刚'},
            {id: 4, name: '小刚'}
        ],
        isError: false,
        errorMessage: ''
    }

    //拦截子组件错误
    static getDerivedStateFromError(error:Error) {
        console.log('error', error.message)
        //返回的内容 会作为state返回
        return {
            errorMessage: error.message,
            isError: true
        }
    }
    //获取子组件的错误信息
    componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
        console.log('error',error)
        console.log('errorInfo',errorInfo)
    }

    //设置子组件数据发生错误
    editError = () => {
        this.setState({
            user_list: undefined
        })
    }

    getUserList(){
        return XEUtils.get(this,'state.user_list') as []
    }

    render() {
        return (
            <div>
                <h5>我是父组件</h5>
                <div>
                    <button onClick={this.editError}>让子组件报错</button>
                </div>
                {
                    this.state.isError ? <ErrorPage message={this.state.errorMessage} /> : <A userList={this.getUserList()}></A>
                }

            </div>
        );
    }
}

class A extends PureComponent {
    static propTypes = {
        userList: PropTypes.array.isRequired
    }
    componentDidMount() {
        console.log(this.props)
    }
    getList(){
        return XEUtils.get(this,'props.userList') as {id:string,name:string}[]
    }


    render() {
        return (
            <div>
                <h5>我是自组件</h5>

                {

                    this.getList().map(n => <div key={n.id}>{n.name}</div>)
                }
            </div>
        );
    }
}
class ErrorPage extends PureComponent {
    static propTypes = {
        message: PropTypes.string.isRequired
    }
    render() {
        return (
            <div className={"error-page"}>
                <div>亲您当前组件错误</div>
                <div>错误内容：{XEUtils.get(this,'props.message') as string}</div>
            </div>
        );
    }
}

export default ErrorCatch;